import axios from 'axios'
import {
	MessageBox,
	Message
} from 'element-ui'
import store from '@/store'

const {
	encrypt
} = require('@/utils/encryption/index');

// create an axios instance
const service = axios.create({
	baseURL: 'http://127.0.0.1:8080/sp-admin/', // url = base url + request url
	timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		var secretKey =
			"MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCB8zUCtSOOmXZebRD5sruf0u2bpO4lSWtYRRTql/pGARg==";
		var publicKey =
			"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEOvZpg/e5BbGJD6Wq8WRb49guWavri2NbQ35leZKTy3zWO0hiWa5q/7Fp3v4n2bEy8Dn57dealCAqROqB2qjcwQ==";
		var satoken = "";
		var gettoken = localStorage.getItem("token");
		if (gettoken) {
			satoken = gettoken;
			config.headers['satoken'] = gettoken;
		}
		config.headers['secretKey'] = secretKey;
		config.headers['publicKey'] = publicKey;
		var time = new Date().getTime();
		config.headers['time'] = time;
		config.headers['sign'] = encrypt(time + secretKey + publicKey + satoken);
		return config;
	},
	error => {
		return Promise.reject(error)
	}
)
// response interceptor
service.interceptors.response.use(
	response => {
		const res = response.data
		if (res.code !== 200) {
			Message({
				message: res.msg || 'Error',
				type: 'error',
				duration: 5 * 1000
			})
			return res;
		}
		Message({
			message: res.msg,
			type: 'success',
			duration: 1000
		})
		return res;
	},
	error => {
		if (error.response) {
			Message({
				message: error.response.data.message || '系统网速有点慢',
				type: 'error',
				duration: 5 * 1000
			});
		} else if (error.request) {
			Message({
				message: 'Network Error',
				type: 'error',
				duration: 5 * 1000
			});
		} else {
			Message({
				message: error.message,
				type: 'error',
				duration: 5 * 1000
			});
		}
		return Promise.reject(error)
	}
)

export default service